<template>
  <div class="wrapper">
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '15px' }" />
    <div>
      <FormPanel ref="from" :list="initForm" :cols="3" :formType="value.type" :labelWidth="120" :isSubmitBtn="false"
        :isCollapse="false" @formChange="changeHandle" />
    </div>

    <!-- 新增附件上传 begin -->
    <BreakSpace label="附件信息" :containerStyle="{ marginBottom: '15px' }" />
    <Spin :spinning="picLoading" tip="Loading...">
      <FilterTable ref="picTable" :columns="picColumns" :dataSource="picFiles" :params="picParams" height="auto"
        :datakey="'records'" :isSelectColumn="false" :isColumnFilter="false" :isPagination="false"
        :onRowSelectChange="selectChange" :onColumnsChange="picColumns => (this.picColumns = picColumns)">
      </FilterTable>
    </Spin>
    <!-- 查看凭证 -->
    <el-image-viewer :url-list="picList" v-show="imagesViewShow" :on-close="closeImagesViewer"></el-image-viewer>
    <!-- 新增附件上传 end -->

    <BreakSpace label="备件列表" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable height="300" ref="dealerRoleTable" :columns="partColumns" :dataSource="partList"
      :isSelectColumn="isSelectColumn" :datakey="'records'" :onSyncTableData="syncPjFun"
      :onColumnsChange="partColumns => (this.partColumns = partColumns)" columnsRef="notification_maintain_info_02">
    </FilterTable>
    <BreakSpace label="审核记录" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable ref="table" :columns="approveColumns" :dataSource="dataList1" :datakey="'records'"
      :isSelectColumn="false" columnsRef="notification_maintain_index_02"
      :onColumnsChange="columns => this.columns = columns">
    </FilterTable>
    <!-- <approveHistory v-model="approvalparams" /> -->

    <BaseDialog :visible.sync="approveDialogFlag" title="1审核原因" width="30%" destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <div style="height:300px">
        <FormPanel ref="from2" :list="initForm2" :cols="3" :formType="value.type" :labelWidth="120" :isSubmitBtn="false"
          :collapse="false" @formChange="changeHandle2" />
      </div>
      <!-- <div :style="{
        textAlign: 'center'
      }">
        <el-button :loading="loadingFlag" @click="saveDialog(saveState)" type="primary">保 存</el-button>
        <el-button @click="closeRefuseDialog()">返 回</el-button>
      </div> -->
    </BaseDialog>
    <div class="dialogBottmView" :style="{
      textAlign: 'center'
    }">
      <el-button :loading="loadingFlag" @click="saveDialog('30591006')" type="primary">审核通过</el-button>
      <el-button :loading="loadingFlag" @click="refuse('30591005')" type="primary">审核驳回</el-button>
      <el-button @click="closeDialog('closeDialog')">返 回</el-button>
    </div>
  </div>
</template>

<script>

import { getFileGroup } from '@/api/partsmanage/common/file';
import { getPartsGroup, postApprove, getApproveRecord, getClaimRefundInfo } from '@/api/partsmanage/claimRefundManage/audit';
// import approveHistory from '../../components/approveHistory';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import config from '@/assets/js/config';

// import { deletePartFileById } from '@/api/partsmanage/aduitOrder/aduitClaim';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import axios from '@/api/fetch';

export default {
  name: 'chaimapproveinfo',
  mixins: [dictionary],
  props: {
    value: {
      type: Object,
      required: true
    },
  },
  components: {
    // approveHistory,
    ElImageViewer
  },
  data() {
    this.saveData = null;
    this.saveData2 = null;
    return {
      type: this.value.type,
      claimid: this.value.data.id,
      initForm: this.initFormFun(),
      initForm2: this.initFormFun2(),
      partColumns: this.creatHeaderPartColumns(),
      approveColumns: this.creatHeaderApproveColumns(),
      partList: [],
      approveRecordList: [],
      isSelectColumn: false,
      approveDialogFlag: false,
      formData: {},
      orderid: '',
      loadingFlag: false,
      saveState: '',
      // spryduty :'',
      bjthlx: '',
      approvalparams: {},
      ACCEPT_AMOUNT: '',
      // aduitePrice: '',
      picLoading: false,
      picColumns: this.createPicTable(),
      picFiles: [],
      picParams: { xtdjid: '', xtfjlx: 'part_rtgoods' },
      uploadPrefix: config.uploadUrl,// 附件上传前缀
      form: { fileList: [] },
      picLimit: 5,
      picList: [],
      imagesViewShow: false,
      dataList1: [],
      auditSwitch: false,
      jhdInfodisabled: false, // 交货单是否隐藏标识
      FUSHU_ACCEPT_MONEY_TIME: 0, // 申请单价是否为负数的次数
      OUTOFRANGE_ACCEPT_MONEY_TIME: 0, // 申请单价超过受理单价单位长度次数Out of range
      partList1: [], // 备件列表信息零时接收


    };
  },
  created() {
    this.init(this.value.data)
    //理赔退货类型为 货损”或“货差”+ 交货单来源为 备件中心仓库 审核按钮置灰（取消）  受理金额 受理数量不可编辑
    if ((this.value.data.claimRefundType == 30571002 || this.value.data.claimRefundType == 30571003) && this.value.data.zjhdly == 30561002) {
      // this.auditSwitch=true
      // this.partColumns.find(x => x.dataIndex === 'PJHSJE').disabled = true;
      this.partColumns.find(x => x.dataIndex === 'ACCEPT_AMOUNT').editable = false;
      this.partColumns.find(x => x.dataIndex === 'ACCEPT_MONEY').editable = false;
    }

    // 理赔退货类型=“退货” 申请原因=“退网退货”或“公司指令退货”  明细页面基本信息区不显示交货单信息
    // if (this.value.data.claimRefundType == 30571001 &&(this.value.data.applyCause ==30581007 || his.value.data.applyCause == 30581008)){
    if (this.value.data.claimRefundType == 30571001 && (this.value.data.applyCause == 30581007 || this.value.data.applyCause == 30581008)) {
      this.jhdInfodisabled = true;
      console.log("交货单信息", this.jhdInfodisabled)
      this.initForm.find(x => x.fieldName === 'zjhdly').hidden = true;
      this.initForm.find(x => x.fieldName === 'bsfyrq').hidden = true;
      this.initForm.find(x => x.fieldName === 'bsqcrq').hidden = true;
      this.initForm.find(x => x.fieldName === 'coNo').hidden = true;
      this.initForm.find(x => x.fieldName === 'traceNo').hidden = true;
      this.initForm.find(x => x.fieldName === 'wsName').hidden = true;
      this.initForm.find(x => x.fieldName === 'wsPerson').hidden = true;
      this.initForm.find(x => x.fieldName === 'wsPhone').hidden = true;
      this.initForm.find(x => x.fieldName === 'bsysdh').hidden = true;
    }



    // this.type = this.value.type
    // console.log(this.value)
  },
  methods: {
    async init(data) {

      console.log('data', data)
      this.applyNum = data.applyNum
      this.id = data.id

      // 明细基本信息
      const refundInfo = await getClaimRefundInfo({ 'id': this.id });
      // this.bjthlx = data.bsthlx
      // 当理赔退货单为H2时理赔退货审核单H2(理赔退货类型=“货损”或“货差”；交货单来源=“备件中心仓库”)，基本信息区有交货单信息，备件信息区不需要厂端受理
      if ((data.claimRefundType == 30571002 || data.claimRefundType == 30571003) && data.zjhdly == 30561002) {
        getPartsGroup({ 'applyNum': this.applyNum }).then(response => {
          this.partList1 = response.data.records
          this.partList1.forEach(info => {

            // 审核的时间受理数量默认 = 0
            info.ACCEPT_AMOUNT = 0;
            // 受理单价默认 = 0
            info.ACCEPT_MONEY = Number(0).toFixed(2);
            // 审核的时间未受理数量默认 = 0
            info.REJECT_AMOUNT = 0;

          });
          this.partList = Object.assign({}, { 'total': this.partList1.length }, {'records': this.partList1});
        });
      }
      // 条件为其他时
      else {
        getPartsGroup({ 'applyNum': this.applyNum }).then(response => {
          this.partList1 = response.data.records
          // 审核的时间受理数量默认 = 申请数量
          this.partList1.forEach(info => {
            if (Number(info.ACCEPT_AMOUNT) === 0) {
              // 审核的时间受理数量默认 = 申请数量
              info.ACCEPT_AMOUNT = info.APPLY_AMOUNT;
            }
            if (Number(info.ACCEPT_MONEY) === 0) {
              // 受理单价默认 = 服务商进价
              info.ACCEPT_MONEY = this.numberFormat(info.XTJGJG);
            }
          });
          this.partList = Object.assign({}, { 'total': this.partList1.length }, {'records': this.partList1});
        });
      }


      // getPartsGroup({ 'applyNum': this.applyNum }).then(response => {
      //   this.partList = response.data.records
      //   // 审核的时间受理数量默认 = 申请数量
      //   this.partList.forEach(info => {
      //     if (Number(info.ACCEPT_AMOUNT) === 0) {
      //        // 审核的时间受理数量默认 = 申请数量
      //       info.ACCEPT_AMOUNT = info.APPLY_AMOUNT;
      //     }
      //     if (Number(info.PJHSJE) === 0) {
      //       // 受理单价默认 = 服务商进价
      //       info.PJHSJE = this.numberFormat(info.XTJGJG);
      //     }
      //   });
      // }),

      getApproveRecord({ 'applyNum': this.applyNum }).then(response => {
        this.dataList1 = response.data.records
      }),
        this.approvalparams.applyNum = this.applyNum
      // this.approvalparams.xtsplx = 'tt_part_rtgoods'
      this.initForm.forEach(x => {
        if (x.fieldName === 'AUDIT_TIME') {
          x.initialValue = moment(data[x.fieldName]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          // x.initialValue = data[x.fieldName];
          x.initialValue = refundInfo.data[x.fieldName];
        }
      });
      getFileGroup({ "xtdjid": this.id, "xtfjlx": "tt_pt_claim_refund" }).then(response => {
        this.picFiles = response.data.records;
        this.picFiles.forEach(x => {
          x.xtwjmc = x.name;
          x.xtwjlj = x.url;
        });
      });
    },
    syncTableFun(val) {
      console.log(val, this.partList)
    },
    //取消操作
    closeDialog(type) {
      this.approveDialogFlag = false
      this.$emit('close', { visible: false, type: type, });
    },
    initFormFun() {
      return [
        {
          type: 'INPUT',
          label: '服务商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
          // rules: [{
          //   required: true,
          //   message: '必填',
          //   trigger: 'blur'
          // }]
        },
        {
          type: 'INPUT',
          label: '服务商简称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
          // rules: [{
          //   required: true,
          //   message: '必填',
          //   trigger: 'blur'
          // }]
        },
        {
          type: 'INPUT',
          label: '申请单号',
          fieldName: 'applyNum',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '理赔退货类型',
          fieldName: 'claimRefundType',
          placeholder: '请选择',
          initialValue: "",
          disabled: true,
          itemList: this.createDictList('3057'),
        },
        {
          type: 'SELECT',
          label: '申请原因',
          fieldName: 'applyCause',
          placeholder: '请选择',
          initialValue: "",
          disabled: true,
          itemList: this.createDictList('3058'),
        },
        {
          type: 'INPUT',
          label: '提报时间',
          fieldName: 'applyTime',
          placeholder: '请输入',
          initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '申请人',
          fieldName: 'applyByName',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '申请人电话',
          fieldName: 'applyPhone',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '交货单号',
          fieldName: 'bsysdh',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '交货单来源',
          fieldName: 'zjhdly',
          placeholder: '请选择',
          initialValue: "",
          disabled: true,
          hidden: false,
          // hidden: this.jhdInfodisabled,
          itemList: this.createDictList('3056'),
        },
        {
          type: 'INPUT',
          label: '发运时间',
          fieldName: 'bsfyrq',
          placeholder: '请输入',
          hidden: false,
          initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '签收时间',
          fieldName: 'bsqcrq',
          placeholder: '请输入',
          hidden: false,
          initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '承运单号',
          fieldName: 'coNo',
          placeholder: '请输入',
          initialValue: '',
          hidden: false,
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流单号',
          fieldName: 'traceNo',
          placeholder: '请输入',
          hidden: false,
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流公司',
          fieldName: 'wsName',
          placeholder: '请输入',
          initialValue: '',
          hidden: false,
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流联系人',
          fieldName: 'wsPerson',
          placeholder: '请输入',
          initialValue: '',
          hidden: false,
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流联系电话',
          fieldName: 'wsPhone',
          placeholder: '请输入',
          hidden: false,
          initialValue: '',
          disabled: true,
        },
        {
          type: 'TEXT_AREA',
          label: '申请说明',
          initialValue: '',
          selfCols: 3,
          maxlength: 150,
          fieldName: 'applyRemark',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          initialValue: '',
          selfCols: 3,
          maxlength: 200,
          fieldName: 'auditRemark',
          placeholder: '请输入...'
        }

        // {
        //   selfCols: 3,
        //   type: 'UPLOAD_FILE',
        //   label: '上传文件',
        //   fieldName: 'uploadFile',
        //   placeholder: '上传文件...',
        //   initialValue: '',
        //   disabled: true,
        //   upload: {
        //     actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
        //     limit: 1,
        //     tipText: '（支持：pdf、rar、jpg、png格式）',
        //     fileTypes: ['pdf', 'rar', 'jpg', 'png'],
        //     data: {bucketType: 'public'}
        //   }
        // }
      ]
    },

    initFormFun2() {
      return [
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'xtspnr',
          placeholder: '请输入',
          initialValue: '',
          selfCols: 3
        }
      ]
    },
    changeHandle(val) {
      this.saveData = val
    },
    changeHandle2(val) {
      this.saveData2 = val
    },
    creatHeaderPartColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        { title: '备件代码', dataIndex: 'BJXMBH', sorter: true },
        { title: '备件名称', dataIndex: 'BJZWMC', sorter: true, summationDataIndex: 'total', summation: true, summationUnit: '(申请品种合计)', },
        { title: '物料组', dataIndex: 'MATERIAL', dictItems: this.createDictList('3054'), sorter: true },
        { title: '服务商进价', dataIndex: 'XTJGJG', sorter: true, precision: 2, numberFormat: true },
        { title: '申请数量', dataIndex: 'APPLY_AMOUNT', sorter: true, summation: true, defaultEditable: true, defaultEditable: true, summation: true, summationUnit: '(申请数量合计)' },
        // { title: '申请单价', dataIndex: 'APPLY_MONEY', sorter: true,precision: 2,numberFormat: true },
        {
          title: '申请金额', dataIndex: 'APPLY_SUMAMOUNT', sorter: true, summation: true, precision: 2, summation: true, summationUnit: '(申请金额合计)', render: props => {
            props.row.APPLY_SUMAMOUNT = this.numberFormat(props.row.APPLY_AMOUNT * props.row.XTJGJG);
            return <span>{props.row.APPLY_SUMAMOUNT}</span>;
          }
        },
        {
          title: '受理单价', dataIndex: 'ACCEPT_MONEY',editType: 'number', editRequired: true, sorter: true, summation: false, editable: true, defaultEditable: true, precision: 2,
          editPattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          rules: [
            // { required: true, validator: numberCheck1, trigger: 'blur' },
            { required: true, message: '请输入正确的保留两位小数的金额', trigger: 'blur' }],
          // render: props => {
          //   props.row.PJHSJE = this.numberFormat(props.row.PJHSJE)
          //     return <span>{props.row.PJHSJE}</span>;
          //   }
        },
        {
          title: '受理数量',
          editType: 'number',
          align: "center",
          editable: true,
          defaultEditable: true,
          summation: true,
          summationUnit: "(受理数量合计)",
          precision: 0,
          dataIndex: 'ACCEPT_AMOUNT',
          min: 0,
          editRequired: true,
        },
        // {
        //   title: '受理数量', dataIndex: 'ACCEPT_AMOUNT', sorter: true, summation: true, editable: true, defaultEditable: true,summation: true,summationUnit: '(受理数量合计)',
        //   filterType: 'number',editPattern: /^[0-9]\d*$/,
        //   rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
        // },
        // 受理金额 = 受理单价 * 受理数量
        {
          title: '受理金额', dataIndex: 'ACCEPT_MONEY_SUM', sorter: true, summation: true, precision: 2, summation: true, summationUnit: '(受理金额合计)', render: props => {
            props.row.ACCEPT_MONEY_SUM = this.numberFormat(props.row.ACCEPT_MONEY * props.row.ACCEPT_AMOUNT);
            return <span>{props.row.ACCEPT_MONEY_SUM}</span>;
          }
        },
        {
          title: '未受理数量', dataIndex: 'REJECT_AMOUNT', sorter: true, summation: true, summation: true, summationUnit: '(不受理数量合计)', render: props => {
            (this.initForm.find(x => x.fieldName === 'zjhdly').initialValue == 30561002 && this.initForm.find(x => x.fieldName === 'claimRefundType').initialValue != 30571001) ? 0 : props.row.REJECT_AMOUNT = props.row.APPLY_AMOUNT - props.row.ACCEPT_AMOUNT;
            return <span>{props.row.REJECT_AMOUNT}</span>;
          }
        },
      ];
    },
    creatHeaderApproveColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        { title: '审核人', dataIndex: 'AUDIT_BYNAME', sorter: true },
        { title: '审核状态', dataIndex: 'AUDIT_STATUS', dictItems: this.createDictList('3059'), sorter: true },
        { title: '审核日期', dataIndex: 'AUDIT_TIME', sorter: true, dateFormat: 'yyyy-MM-dd HH:mm:ss', },
        { title: '审核意见', dataIndex: 'AUDIT_REMARK', sorter: true }
      ];
    },


    closeRefuseDialog() {
      this.approveDialogFlag = false
    },
    async refuse(state) {
      this.saveState = state
      if (state == '30591005') {
        let json = this.$refs.from.SUBMIT_FORM();
        if (json) {
          let apply = JSON.parse(JSON.stringify(json));
          console.log('驳回提交的表单信息apply', apply)
          apply.AUDIT_STATUS = Number(state);


          if (apply.auditRemark == null || apply.auditRemark === '') {
            this.$notify({
              title: '警告',
              message: '驳回审核意见不能为空',
              type: 'warning',
            });
            return;
          }

          let res = await postApprove(apply)
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '厂端审核驳回成功!' });
            this.approveDialogFlag = false
            this.closeDialog('refresh')

          } else {
            // this.closeDialog('refresh')
            // this.$notify.error({title: '提示信息',message:res.errMsg||'审核失败!'});
          }
          // this.loadingFlag = false;
        }
      }

    },
    async saveDialog(val) {
      let reason = '审核通过'

      let json = this.$refs.from.SUBMIT_FORM();
      if (json) {
        let apply = JSON.parse(JSON.stringify(json));
        console.log('apply', apply)

        // 当理赔退货单为H2时理赔退货审核单H2(理赔退货类型=“货损”或“货差”；交货单来源=“备件中心仓库”) 不对受理数量合计做非0校验提示
        if ((apply.claimRefundType == 30571002 || apply.claimRefundType == 30571003) && apply.zjhdly == 30561002) {
          if (apply.auditRemark == null || apply.auditRemark === '') {
            this.$notify({
              title: '警告',
              message: '审核意见不能为空',
              type: 'warning',
            });
            return;
          }
        } else {
          if (apply.auditRemark == null || apply.auditRemark === '') {
            this.$notify({
              title: '警告',
              message: '审核意见不能为空',
              type: 'warning',
            });
            return;
          }

          let ACCEPT_AMOUNT_HJ = 0;
          this.partList.records.forEach(x => {
            console.log("x", x)
            ACCEPT_AMOUNT_HJ += Number(x.ACCEPT_AMOUNT);
            if (x.ACCEPT_MONEY < 0) {
              this.FUSHU_ACCEPT_MONEY_TIME += 1;
            }
            // 9位数 + 1位小数点 + 2位小数
            if (x.ACCEPT_MONEY.length > 12) {
              console.log("OUTOFRANGE_ACCEPT_MONEY_TIME", x)
              this.OUTOFRANGE_ACCEPT_MONEY_TIME += 1;
            }
            // if(x.ACCEPT_AMOUNT>x.APPLY_AMOUNT){
            //   this.$notify({ title: '提示信息', message: '备件列表第' + Number(x.index + 1) + '行受理数量不能大于申请数量' ,type: 'warning',});
            //   return;
            //   }

          })
          console.log("shodsdsada", ACCEPT_AMOUNT_HJ)
          if (ACCEPT_AMOUNT_HJ === 0) {
            this.$notify({
              title: '警告',
              message: '受理数量合计不能为0',
              type: 'warning',
            });
            return;
          }

        }



      }



      //   let numCheck = this.saveData.partList.find(item => Number(item.ACCEPT_AMOUNT) < Number(item.APPLY_AMOUNT))
      //   if (numCheck) {
      // this.$notify.error({ title: '提示信息', message: '备件信息第' + Number(numCheck.index + 1) + '行受理数量不能大于申请数量' });
      // this.loadingFlag = false;
      // return false;
      // }
      console.log('审核信息', this.saveData)
      console.log('备件信息', this.saveData.partList)
      // let res = await postApprove(this.saveData)

      if (this.saveData) {
        this.loadingFlag = true

        // this.saveData.type = this.type
        // this.saveData.xsddzt = val
        this.saveData.partList = this.formData.details
        this.saveData.AUDIT_STATUS = val;
        // this.saveData.id = this.claimid
        // let part = this.saveData.partList.find(item => Number(item.cmsAduitNum) <= 0)
        //   // console.log(JSON.stringify(part));
        // let numCheck = this.saveData.partList.find(item => Number(item.bsthsl) < item.cmsAduitNum)
        // console.log(JSON.stringify(numCheck));
        // if (part) {
        //   this.$notify.error({ title: '提示信息', message: '备件信息第' + Number(part.index + 1) + '行审核数量不能为0' });
        //   this.loadingFlag = false;
        //   return false;
        // }
        // if (numCheck) {
        //   this.$notify.error({ title: '提示信息', message: '备件信息第' + Number(numCheck.index + 1) + '行审核数量不能大于申请数量' });
        //   this.loadingFlag = false;
        //   return false;
        // }
        if (this.FUSHU_ACCEPT_MONEY_TIME == 0) {
          if (this.OUTOFRANGE_ACCEPT_MONEY_TIME == 0){
            let res = await postApprove(this.saveData)
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '厂端审核通过!' });
            this.approveDialogFlag = false
            this.closeDialog('refresh')
          } else {
            this.loadingFlag = false;
            // this.closeDialog('refresh')
            // this.$notify.error({title: '提示信息',message:res.errMsg||'审核失败!'});
          }
          }else {
            this.OUTOFRANGE_ACCEPT_MONEY_TIME = 0;
          this.loadingFlag = false;
          this.$notify({
            title: '警告',
            message: '受理单价不能超过九位数',
            type: 'warning',
          });
          return;
          }

        } else {
          this.FUSHU_ACCEPT_MONEY_TIME = 0;
          this.loadingFlag = false;
          this.$notify({
            title: '警告',
            message: '受理单价不能为负数',
            type: 'warning',
          });
          return;

        }




      }
    },
    syncPjFun(details) {
      console.log('details', details)
      this.formData.details = details
    },
    numberFormat(input) {
      if (!isNaN(Number(input))) {
        input = Number(input).toFixed(2);
      }
      input = this.formatNumber(input);
      return input
    },
    // 数字格式化
    formatNumber(value) {
      value += '';
      if (value.slice(-1) === '.') return value;
      value = value.replace(/,\s+/g, '');
      const list = value.split('.');
      const prefix = list[0].charAt(0) === '-' ? '-' : '';
      let num = prefix ? list[0].slice(1) : list[0];
      let result = '';
      while (num.length > 3) {
        result = `, ${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
      }
      if (num) {
        result = num + result;
      }
      return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
    },

    createPicTable() {
      return [
        {
          title: '序号', dataIndex: 'index', width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作', dataIndex: 'column-action', width: 150, align: 'center',
          hidden: true,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deletePic(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '图片（支持格式：jpg, jpeg, png;）', dataIndex: 'name', align: 'center',
          render: p => {
            let fileType = this.getFileType(p.row.url);
            return fileType == 'pdf' ? (
              <a href={p.row.url} target="_blank">{p.row.name}</a>
            ) :
              (
                <div class="imgfile">
                  <img src={p.row.url} onClick={() => { this.imagesViewShow = true; this.picList = [p.row.url] }} alt="" />
                  <a href={p.row.url} target="_blank">{p.row.name}</a>
                </div>
              );
          }
        }
      ]
    },
    async deletePic(val) {
      this.$confirm('确定删除此文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let picIndex = 0;
        if (val.id != null && val.id > 0) {
          const res = await deletePartFileById(val.id, "part_rtgoods");
          if (res.resultCode === 200) {
            this.$refs.picTable.$refs.pageTable.EXECUTE_DELETE([val]);
            this.picFiles.forEach(x => {
              this.$set(x, 'index', picIndex++);
            });
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
          }
        } else {
          this.$refs.picTable.$refs.pageTable.EXECUTE_DELETE([val]);
          this.picFiles.forEach(x => {
            this.$set(x, 'index', picIndex++);
          });
          this.$notify.success({ title: '提示信息', message: '删除成功!' });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    selectChange(val) {
      console.log('val', val);
    },
    // 上传成功回调
    successHandler(val) {
      if (val == 1) {
        this.picLoading = true;
      } else {
        this.picLoading = false;
        let data = { index: '', name: '', url: '', xtwjmc: '', xtwjlj: '' };
        let json = JSON.parse(JSON.stringify(val));
        this.$set(data, 'index', this.picFiles.length);
        this.$set(data, 'name', json[json.length - 1].name);
        this.$set(data, 'xtwjmc', json[json.length - 1].name);
        let furl = json[json.length - 1].url;
        this.$set(data, 'xtwjlj', furl);
        this.$set(data, 'url', furl);
        this.picFiles.push(data);
      }
    },
    async getPicUrl(url) {
      let actionUrl = this.uploadPrefix + '/api/file/download/url?fileUrl=' + url;
      let res = await axios.post(actionUrl);
      return res.data;
    },
    getFileType(fileName) {
      let fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
      return fileType.toLowerCase().split("?")[0];
    },
    closeImagesViewer() {
      this.imagesViewShow = false;
    },
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}

.el-table__body-wrapper {
  overflow-x: auto;
  position: static;
}

.el-image {
  float: left;
  margin-left: 130px;
}

.imgfile {
  height: 60px;
  line-height: 60px;
  overflow: hidden;
}

.imgfile a {
  float: left;
  margin-left: 20px;
}

.imgfile img {
  float: left;
  margin-left: 30%;
  width: 100px;
  height: 100%;
  object-fit: cover;
}

.pdfdiv {
  float: left;
  margin-left: 20%;
  width: 100px;
  height: 100%;
  object-fit: cover;
}
</style>
